package com.jxs.easysecurity.token.impl;

import com.jxs.easysecurity.exception.AccessTokenResolveException;
import com.jxs.easysecurity.token.AccessTokenEx;
import com.jxs.easysecurity.token.AccessTokenFactory;
import com.jxs.easysecurity.token.TokenMergeInfo;
import com.jxs.easysecurity.utils.CipherKit;
import org.apache.commons.lang3.StringUtils;

/**
 * @author jiangxingshang
 * @since 17/6/20
 */
public class DefaultAccessTokenFactory implements AccessTokenFactory {

    private CipherKit secretKit;

    public DefaultAccessTokenFactory(String secretKey) {
        secretKit = new CipherKit(secretKey);
    }

    @Override
    public AccessTokenEx build(String sessionId, long timeout, TokenMergeInfo info) {
        String extra = info == null ? "" : StringUtils.defaultString(info.getMergeInfo());
        String content = StringUtils.join(new String[] {sessionId, timeout + ""}, ',') + ":" + extra;
        String token = secretKit.encode(content);
        return new AccessTokenEx(token, sessionId, timeout, extra);
    }

    @Override
    public AccessTokenEx resolve(String token) throws AccessTokenResolveException {
        try {
            if(StringUtils.isBlank(token)) {
                throw new IllegalArgumentException("Access token is empty.");
            }
            String content = secretKit.decode(token);
            if(content == null) {
                throw new Exception("Cannot decode access token - " + token);
            }
            int index = content.indexOf(":");
            String[] tmp = content.substring(0, index).split(",");
            String sessionId = tmp[0];
            long timeout = Long.parseLong(tmp[1]);
            String extra = index + 1 < content.length() ? content.substring(index + 1, content.length()) : null;
            return new AccessTokenEx(token, sessionId, timeout, extra);
        } catch(Exception e) {
            throw new AccessTokenResolveException(e);
        }
    }
}
